package com.lagou.edu.servlet;

import com.lagou.edu.constant.Result;
import com.lagou.edu.ioc.ClassPathXmlBeanFactory;
import com.lagou.edu.service.ITransferService;
import com.lagou.edu.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Kirito
 * @description:
 * @date 2020/04/04
 */
@WebServlet(name = "transferServlet", urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {

    //private ITransferService transferService = new TransferServiceImpl();

    //private ITransferService transferService = (ITransferService) BeanFactory.getObject("transferService");

    //private ProxyFactory proxyFactory = (ProxyFactory) BeanFactory.getObject("proxyFactory");
    //获取ITransferService经过代理后的对象来处理事务
    // private ITransferService transferService = (ITransferService) proxyFactory.createJdkProxy(BeanFactory.getObject("transferService"));

    private ClassPathXmlBeanFactory beanFactory = ClassPathXmlBeanFactory.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置字符集
        req.setCharacterEncoding("utf-8");

        // 获取请求参数
        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        int money = Integer.parseInt(req.getParameter("money"));

        // 封装调用结果
        Result result = new Result();
        try {
            ITransferService transferService = (ITransferService) beanFactory.getBean("transferServiceImpl");
            transferService.transfer(fromCardNo, toCardNo, money);
            result.setStatus("200");
            result.setMessage("转账成功！");
        } catch (Exception e) {
            //e.printStackTrace();
            result.setStatus("500");
            result.setMessage(e.getMessage());
        }

        // 设置响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));
    }
}
